import { getMessageCodeAPI } from '@/api/login'

export default {
  data() {
    return {
      codeButtonInfo: { // 验证码按钮
        time: undefined,
        count: 60,
        text: '获取验证码',
        canClick: true
      }
    }
  },
  computed: {},
  methods: {
    handleGetMessageCode() { // 获取短信验证码
      let { canClick } = this.codeButtonInfo
      if (!canClick) return false // 判断当前按钮能否点击
      this.codeButtonInfo.canClick = false // 接口请求时间段不能重复点击按钮
      this.getMessageCodeData()
      /* if (!this.validatePhone()) {
        this.resetCodeButton()
      } else {
      } */
    },
    resetCodeButton() { // 验证码按钮初始化
      clearInterval(this.codeButtonInfo.time)
      this.codeButtonInfo.canClick = true
      this.codeButtonInfo.text = '获取验证码'
      this.codeButtonInfo.count = 60
    },
    async getMessageCodeData() { // 获取验证码请求接口
      try {
        let { username, password } = this.loginForm
        let response = await getMessageCodeAPI({
          username,
          password
        })
        let result = response
        if (+result.code === 200) {
          // 开始倒计时
          this.codeButtonInfo.text = `${this.codeButtonInfo.count}s后获取`
          this.codeButtonInfo.time = setInterval(() => {
            this.codeButtonInfo.count -= 1
            if (this.codeButtonInfo.count === 0) {
              this.resetCodeButton()
            } else {
              this.codeButtonInfo.text = `${this.codeButtonInfo.count}s后获取`
            }
          }, 1000)
          this.$notify.success({
            title: '成功',
            message: `发送到手机号为：${this.currentPhone}了` || '发送成功！'
          })
        } else {
          this.resetCodeButton()
          this.$notify.error({
            title: '错误',
            message: result.msg || '获取验证码失败！'
          })
        }
      } catch (error) {
        // console.log(error)
        this.resetCodeButton()
        this.$notify.error({
          title: '错误',
          message: error.message || '获取验证码失败!'
        })
      }
    }
  }
}
